package com.xul.crowd.config;

import com.xul.crowd.entity.Admin;
import com.xul.crowd.entity.Role;
import com.xul.crowd.service.AdminService;
import com.xul.crowd.service.AuthService;
import com.xul.crowd.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xul
 * @create 2021-07-27 15:31
 */

@Component
public class CrowdUserDetailService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    @Override
    public UserDetails loadUserByUsername(String loginAcct) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        Admin admin = adminService.getAdminByLoginAcct(loginAcct);
        Integer adminId = admin.getId();
        List<Role> assignRoleList = roleService.getAssignRole(adminId);
        List<String> assignedAuthNameList = authService.getAssignedAuthNameByAminId(adminId);
        // 创建集合对象用来存储GrantedAuthority
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 遍历assignedRoleList存入角色信息
        for (Role role : assignRoleList) {
            // 注意角色不要忘记加前缀 对角色经行封装
            String roleName = "ROLE_" + role.getName();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            authorities.add(simpleGrantedAuthority);
        }
        // 遍历authNameList存入权限信息
        for (String authName : assignedAuthNameList) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);
            authorities.add(simpleGrantedAuthority);
        }
        // 封装SecurityAdmin对象
        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);
        return securityAdmin;
    }
}
